package 并发编程12.读写锁测试.锁的降级测试;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author idea
 * @data 2019/2/19
 */
public class MyDemotionLock {

    private Map<String,Object> map=new HashMap<>();

    private ReadWriteLock rw1=new ReentrantReadWriteLock();

    private Lock r=rw1.readLock();

    private Lock w=rw1.writeLock();

    int value=100;

    public void readAndWrite(){
        r.lock();

        Object obj=map.get("a");
        if(obj==null){
            System.out.println("获取到了null");
            r.unlock();
            w.lock();
            map.put("a","cassaasqw");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            w.unlock();
            System.out.println("我要释放锁啦！");
            r.lock();
        }
        System.out.println("线程"+Thread.currentThread().getName()+map.get("a"));
        r.unlock();
    }


    public static void main(String[] args) {
        MyDemotionLock lock = new MyDemotionLock();
        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName()+"启动");
            lock.readAndWrite();
        };
        Thread[] threadArray = new Thread[10];
        for (int i=0; i<10; i++) {
            threadArray[i] = new Thread(runnable);
        }
        for (int i=0; i<10; i++) {
            threadArray[i].start();
        }
    }


}
